import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'dart:async' show Future;

class AttentionPageWidget extends StatefulWidget {
  @override
  _AttentionPageWidgetState createState() => _AttentionPageWidgetState();
}

class _AttentionPageWidgetState extends State<AttentionPageWidget> {
  dynamic data;

  @override
  void initState() {
    super.initState();
    _loadJson();
  }

  Future<String> loadAsset() async {
    return await rootBundle
        .loadString('assets/fake/json_discovery_attention.json');
  }

  @override
  Widget build(BuildContext context) {
    double leftRightMargin = 15;
    double picDivideWidth = 4.5;
    double screenWidth = MediaQuery.of(context).size.width;
    double smallPicWidth =
        (screenWidth - 2 * leftRightMargin - 2 * picDivideWidth) / 3;
    List<Widget> widgetList;
    if (data != null && data.length > 0) {
      widgetList = List();
      for (int i = 0; i < data.length; i++) {
        widgetList.add(AttentionArticleWidget(
          itemBean: data[i],
          smallPicWidth: smallPicWidth,
          leftRightMaring: leftRightMargin,
        ));
      }
    }
    return Container(
        child: widgetList != null
            ? ListView(children: widgetList)
            : Center(child: Text("Loading")));
  }

  void _loadJson() {
    loadAsset().then((json) {
      JsonDecoder decoder = new JsonDecoder();
      var result = decoder.convert(json);
      var list = List();
      if (result is List) {
        list.addAll(result);
        list.addAll(result);
        list.addAll(result);
        list.addAll(result);
        list.addAll(result);
      }
      setState(() {
        data = list;
      });
    });
  }
}

class AttentionArticleWidget extends StatelessWidget {
  final dynamic itemBean;
  final double smallPicWidth;
  final double leftRightMaring;

  const AttentionArticleWidget(
      {this.itemBean, this.smallPicWidth, this.leftRightMaring})
      : assert(itemBean != null);

  Widget _buildHeaderLayout(BuildContext context) {
    return Container(
        margin: EdgeInsets.only(bottom: 10, top: 10),
        child: Row(children: <Widget>[
          CircleAvatar(
            backgroundImage: NetworkImage(itemBean['author']['avatar']),
            radius: 20,
          ),
          Container(
              margin: EdgeInsets.only(left: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    itemBean['author']['name'],
                    style:
                        TextStyle(fontSize: 14, color: const Color(0xff333333)),
                  ),
                  Container(
                    height: 6,
                  ),
                  Text(itemBean['update_time'],
                      style: TextStyle(
                          fontSize: 10, color: const Color(0xff999999)))
                ],
              ))
        ]));
  }

  Widget _buildContentTitle(BuildContext context) {
    return Text(
      itemBean['title'],
      maxLines: 2,
      style: TextStyle(color: Color(0xff333333), fontSize: 18),
    );
  }

  Widget _buildContentDesc(BuildContext context) {
    return Text(
      "${itemBean['comment_num']}评论",
      maxLines: 1,
      style: TextStyle(fontSize: 12, color: Color(0xff999999)),
    );
  }

  Widget _netWorkBorderRadiusImage(String url, double width, double height) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(2)),
          image: DecorationImage(image: NetworkImage(url), fit: BoxFit.cover),
          border: Border.all(color: const Color(0xffeeeeee), width: 0.5)),
    );
  }

  Widget _buildOnePicContent(BuildContext context) {
    List<Widget> titleChildren = new List();
    titleChildren.add(Expanded(child: _buildContentTitle(context)));
    if (itemBean['comment_num'] > 0) {
      titleChildren.add(_buildContentDesc(context));
    }
    return Container(
      height: smallPicWidth * 3 / 4,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: titleChildren,
          )),
          Container(width: 10),
          _netWorkBorderRadiusImage(
              itemBean['cover_url'][0], smallPicWidth, smallPicWidth * 3 / 4),
        ],
      ),
    );
  }

  Widget _buildThreePicContent(BuildContext context) {
    return Container(
        margin: EdgeInsets.only(top: 12),
        height: smallPicWidth,
        child: Row(children: <Widget>[
          _netWorkBorderRadiusImage(
              itemBean['cover_url'][0], smallPicWidth, smallPicWidth),
          Expanded(
              child: Center(
                  child: _netWorkBorderRadiusImage(
                      itemBean['cover_url'][1], smallPicWidth, smallPicWidth))),
          _netWorkBorderRadiusImage(
              itemBean['cover_url'][2], smallPicWidth, smallPicWidth),
        ]));
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> childViews = List();
    //头部布局
    Widget headerView = _buildHeaderLayout(context);
    childViews.add(headerView);
    //单图
    if (itemBean['cover_url'] != null && itemBean['cover_url'].length == 1 ||
        itemBean['cover_url'].length == 2) {
      Widget onePicView = _buildOnePicContent(context);
      childViews.add(onePicView);
    } else {
      ////三图或无图
      childViews.add(_buildContentTitle(context));
      //三图
      if (itemBean['cover_url'] != null && itemBean['cover_url'].length >= 3) {
        childViews.add(_buildThreePicContent(context));
      }
      if (itemBean['comment_num'] > 0) {
        childViews.add(Container(
            child: _buildContentDesc(context),
            alignment: Alignment.centerLeft));
      }
    }
    childViews.add(Container(height: 14));
    childViews.add(Divider(
      height: 1,
    ));

    ///纵向列布局
    return Container(
        margin: EdgeInsets.only(left: leftRightMaring, right: leftRightMaring),
        child: Column(
          children: childViews,
        ));
  }
}

class AttentionMusicVideoWidget extends StatelessWidget {
  final dynamic itemBean;
  final int type; //1听听,2看看

  const AttentionMusicVideoWidget({Key key, this.itemBean, this.type})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
